<template>
  <div class="bank-info-manager">
    <div class="card">
      <div class="card-header">
        <h5 class="mb-0">
          <i class="bi bi-bank text-primary me-2"></i>
          银行信息管理
        </h5>
      </div>
      <div class="card-body">
        <!-- 添加新银行信息 -->
        <div class="row mb-4">
          <div class="col-12">
            <h6 class="text-secondary mb-3">
              <i class="bi bi-plus-circle me-2"></i>
              添加新银行信息
            </h6>
            <form @submit.prevent="addBankInfo">
              <div class="row">
                <div class="col-md-4 mb-3">
                  <label class="form-label">银行标准名称 <span class="text-danger">*</span></label>
                  <input 
                    type="text" 
                    class="form-control" 
                    v-model="newBank.standardName"
                    placeholder="如：中国邮政储蓄银行"
                    required
                  >
                </div>
                <div class="col-md-4 mb-3">
                  <label class="form-label">银行简称</label>
                  <input 
                    type="text" 
                    class="form-control" 
                    v-model="newBank.shortName"
                    placeholder="如：邮储银行"
                  >
                </div>
                <div class="col-md-4 mb-3">
                  <label class="form-label">英文简称</label>
                  <input 
                    type="text" 
                    class="form-control" 
                    v-model="newBank.englishName"
                    placeholder="如：PSBC"
                  >
                </div>
              </div>
              <div class="row">
                <div class="col-md-6 mb-3">
                  <label class="form-label">BIN码（前6位）</label>
                  <input 
                    type="text" 
                    class="form-control" 
                    v-model="newBank.binCode"
                    placeholder="如：621096"
                    maxlength="6"
                    pattern="[0-9]{6}"
                  >
                  <div class="form-text">银行卡号前6位数字</div>
                </div>
                <div class="col-md-6 mb-3">
                  <label class="form-label">卡号长度规范</label>
                  <input 
                    type="text" 
                    class="form-control" 
                    v-model="newBank.cardLengthRule"
                    placeholder="如：16-19位"
                  >
                  <div class="form-text">该银行卡号的标准长度</div>
                </div>
              </div>
              <div class="row">
                <div class="col-12 mb-3">
                  <label class="form-label">其他别名（用逗号分隔）</label>
                  <textarea 
                    class="form-control" 
                    v-model="newBank.aliases"
                    rows="2"
                    placeholder="如：邮政银行,邮储,PSBC,中国邮政储蓄银行股份有限公司"
                  ></textarea>
                  <div class="form-text">用户可能输入的其他银行名称变体</div>
                </div>
              </div>
              <div class="d-flex justify-content-end">
                <button type="button" class="btn btn-secondary me-2" @click="resetForm">
                  <i class="bi bi-arrow-clockwise me-1"></i>
                  重置
                </button>
                <button type="submit" class="btn btn-primary">
                  <i class="bi bi-plus-lg me-1"></i>
                  添加银行
                </button>
              </div>
            </form>
          </div>
        </div>

        <hr>

        <!-- 现有银行信息列表 -->
        <div class="row">
          <div class="col-12">
            <h6 class="text-secondary mb-3">
              <i class="bi bi-list-ul me-2"></i>
              现有银行信息 ({{ customBanks.length }})
            </h6>
            
            <!-- 搜索过滤 -->
            <div class="row mb-3">
              <div class="col-md-6">
                <div class="input-group">
                  <span class="input-group-text">
                    <i class="bi bi-search"></i>
                  </span>
                  <input 
                    type="text" 
                    class="form-control" 
                    v-model="searchKeyword"
                    placeholder="搜索银行名称或BIN码"
                  >
                </div>
              </div>
              <div class="col-md-6">
                <button class="btn btn-outline-primary" @click="exportBankData">
                  <i class="bi bi-download me-1"></i>
                  导出数据
                </button>
                <button class="btn btn-outline-secondary ms-2" @click="importBankData">
                  <i class="bi bi-upload me-1"></i>
                  导入数据
                </button>
                <input 
                  type="file" 
                  ref="fileInput" 
                  @change="handleFileImport" 
                  accept=".json"
                  style="display: none;"
                >
              </div>
            </div>

            <!-- 银行列表 -->
            <div class="table-responsive">
              <table class="table table-hover">
                <thead class="table-light">
                  <tr>
                    <th>标准名称</th>
                    <th>简称</th>
                    <th>英文简称</th>
                    <th>BIN码</th>
                    <th>卡号长度</th>
                    <th>别名</th>
                    <th>操作</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(bank, index) in filteredBanks" :key="index">
                    <td>
                      <strong class="text-primary">{{ bank.standardName }}</strong>
                    </td>
                    <td>{{ bank.shortName || '-' }}</td>
                    <td>{{ bank.englishName || '-' }}</td>
                    <td>
                      <span v-if="bank.binCode" class="badge bg-info">{{ bank.binCode }}</span>
                      <span v-else class="text-muted">-</span>
                    </td>
                    <td>{{ bank.cardLengthRule || '-' }}</td>
                    <td>
                      <div v-if="bank.aliases && bank.aliases.length > 0">
                        <span 
                          v-for="alias in bank.aliases.slice(0, 3)" 
                          :key="alias"
                          class="badge bg-secondary me-1 mb-1"
                        >
                          {{ alias }}
                        </span>
                        <span v-if="bank.aliases.length > 3" class="text-muted small">
                          +{{ bank.aliases.length - 3 }}个
                        </span>
                      </div>
                      <span v-else class="text-muted">-</span>
                    </td>
                    <td>
                      <button 
                        class="btn btn-sm btn-outline-primary me-1" 
                        @click="editBank(index)"
                        title="编辑"
                      >
                        <i class="bi bi-pencil"></i>
                      </button>
                      <button 
                        class="btn btn-sm btn-outline-danger" 
                        @click="deleteBank(index)"
                        title="删除"
                      >
                        <i class="bi bi-trash"></i>
                      </button>
                    </td>
                  </tr>
                  <tr v-if="filteredBanks.length === 0">
                    <td colspan="7" class="text-center text-muted py-4">
                      <i class="bi bi-inbox display-6 d-block mb-2"></i>
                      {{ searchKeyword ? '未找到匹配的银行信息' : '暂无自定义银行信息' }}
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 编辑银行信息模态框 -->
    <div class="modal fade" id="editBankModal" tabindex="-1">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">
              <i class="bi bi-pencil-square me-2"></i>
              编辑银行信息
            </h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
          </div>
          <div class="modal-body">
            <form @submit.prevent="updateBank">
              <div class="row">
                <div class="col-md-6 mb-3">
                  <label class="form-label">银行标准名称 <span class="text-danger">*</span></label>
                  <input 
                    type="text" 
                    class="form-control" 
                    v-model="editingBank.standardName"
                    required
                  >
                </div>
                <div class="col-md-6 mb-3">
                  <label class="form-label">银行简称</label>
                  <input 
                    type="text" 
                    class="form-control" 
                    v-model="editingBank.shortName"
                  >
                </div>
              </div>
              <div class="row">
                <div class="col-md-6 mb-3">
                  <label class="form-label">英文简称</label>
                  <input 
                    type="text" 
                    class="form-control" 
                    v-model="editingBank.englishName"
                  >
                </div>
                <div class="col-md-6 mb-3">
                  <label class="form-label">BIN码（前6位）</label>
                  <input 
                    type="text" 
                    class="form-control" 
                    v-model="editingBank.binCode"
                    maxlength="6"
                    pattern="[0-9]{6}"
                  >
                </div>
              </div>
              <div class="row">
                <div class="col-md-6 mb-3">
                  <label class="form-label">卡号长度规范</label>
                  <input 
                    type="text" 
                    class="form-control" 
                    v-model="editingBank.cardLengthRule"
                  >
                </div>
              </div>
              <div class="row">
                <div class="col-12 mb-3">
                  <label class="form-label">其他别名（用逗号分隔）</label>
                  <textarea 
                    class="form-control" 
                    v-model="editingBank.aliasesText"
                    rows="3"
                  ></textarea>
                </div>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
              取消
            </button>
            <button type="button" class="btn btn-primary" @click="updateBank">
              <i class="bi bi-check-lg me-1"></i>
              保存更改
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { Modal } from 'bootstrap'

export default {
  name: 'BankInfoManager',
  setup() {
    // 响应式数据
    const customBanks = ref([])
    const searchKeyword = ref('')
    const editingIndex = ref(-1)
    const fileInput = ref(null)
    
    // 新银行信息表单
    const newBank = ref({
      standardName: '',
      shortName: '',
      englishName: '',
      binCode: '',
      cardLengthRule: '',
      aliases: ''
    })
    
    // 编辑银行信息
    const editingBank = ref({
      standardName: '',
      shortName: '',
      englishName: '',
      binCode: '',
      cardLengthRule: '',
      aliasesText: ''
    })
    
    // 计算属性
    const filteredBanks = computed(() => {
      if (!searchKeyword.value) {
        return customBanks.value
      }
      
      const keyword = searchKeyword.value.toLowerCase()
      return customBanks.value.filter(bank => {
        return bank.standardName.toLowerCase().includes(keyword) ||
               (bank.shortName && bank.shortName.toLowerCase().includes(keyword)) ||
               (bank.englishName && bank.englishName.toLowerCase().includes(keyword)) ||
               (bank.binCode && bank.binCode.includes(keyword)) ||
               (bank.aliases && bank.aliases.some(alias => alias.toLowerCase().includes(keyword)))
      })
    })
    
    // 方法
    const loadCustomBanks = () => {
      const saved = localStorage.getItem('customBankInfo')
      if (saved) {
        try {
          customBanks.value = JSON.parse(saved)
        } catch (error) {
          console.error('加载自定义银行信息失败:', error)
          customBanks.value = []
        }
      }
    }
    
    const saveCustomBanks = () => {
      localStorage.setItem('customBankInfo', JSON.stringify(customBanks.value))
    }
    
    const addBankInfo = () => {
      if (!newBank.value.standardName.trim()) {
        alert('请输入银行标准名称')
        return
      }
      
      // 检查是否已存在
      const exists = customBanks.value.some(bank => 
        bank.standardName === newBank.value.standardName.trim()
      )
      
      if (exists) {
        alert('该银行已存在')
        return
      }
      
      // 处理别名
      const aliases = newBank.value.aliases
        .split(',')
        .map(alias => alias.trim())
        .filter(alias => alias.length > 0)
      
      // 添加新银行
      const bankInfo = {
        standardName: newBank.value.standardName.trim(),
        shortName: newBank.value.shortName.trim() || null,
        englishName: newBank.value.englishName.trim() || null,
        binCode: newBank.value.binCode.trim() || null,
        cardLengthRule: newBank.value.cardLengthRule.trim() || null,
        aliases: aliases.length > 0 ? aliases : null,
        createdAt: new Date().toISOString()
      }
      
      customBanks.value.push(bankInfo)
      saveCustomBanks()
      resetForm()
      
      // 触发银行信息更新事件
      updateBankValidator()
      
      alert('银行信息添加成功！')
    }
    
    const resetForm = () => {
      newBank.value = {
        standardName: '',
        shortName: '',
        englishName: '',
        binCode: '',
        cardLengthRule: '',
        aliases: ''
      }
    }
    
    const editBank = (index) => {
      editingIndex.value = index
      const bank = customBanks.value[index]
      
      editingBank.value = {
        standardName: bank.standardName,
        shortName: bank.shortName || '',
        englishName: bank.englishName || '',
        binCode: bank.binCode || '',
        cardLengthRule: bank.cardLengthRule || '',
        aliasesText: bank.aliases ? bank.aliases.join(', ') : ''
      }
      
      const modal = new Modal(document.getElementById('editBankModal'))
      modal.show()
    }
    
    const updateBank = () => {
      if (editingIndex.value === -1) return
      
      // 处理别名
      const aliases = editingBank.value.aliasesText
        .split(',')
        .map(alias => alias.trim())
        .filter(alias => alias.length > 0)
      
      // 更新银行信息
      customBanks.value[editingIndex.value] = {
        ...customBanks.value[editingIndex.value],
        standardName: editingBank.value.standardName.trim(),
        shortName: editingBank.value.shortName.trim() || null,
        englishName: editingBank.value.englishName.trim() || null,
        binCode: editingBank.value.binCode.trim() || null,
        cardLengthRule: editingBank.value.cardLengthRule.trim() || null,
        aliases: aliases.length > 0 ? aliases : null,
        updatedAt: new Date().toISOString()
      }
      
      saveCustomBanks()
      updateBankValidator()
      
      // 关闭模态框
      const modal = Modal.getInstance(document.getElementById('editBankModal'))
      modal.hide()
      
      alert('银行信息更新成功！')
    }
    
    const deleteBank = (index) => {
      if (confirm('确定要删除这个银行信息吗？')) {
        customBanks.value.splice(index, 1)
        saveCustomBanks()
        updateBankValidator()
        alert('银行信息删除成功！')
      }
    }
    
    const exportBankData = () => {
      const data = {
        banks: customBanks.value,
        exportTime: new Date().toISOString(),
        version: '1.0'
      }
      
      const blob = new Blob([JSON.stringify(data, null, 2)], {
        type: 'application/json'
      })
      
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `custom-banks-${new Date().toISOString().split('T')[0]}.json`
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
    }
    
    const importBankData = () => {
      fileInput.value.click()
    }
    
    const handleFileImport = (event) => {
      const file = event.target.files[0]
      if (!file) return
      
      const reader = new FileReader()
      reader.onload = (e) => {
        try {
          const data = JSON.parse(e.target.result)
          
          if (data.banks && Array.isArray(data.banks)) {
            // 合并银行数据，避免重复
            const existingNames = new Set(customBanks.value.map(b => b.standardName))
            const newBanks = data.banks.filter(b => !existingNames.has(b.standardName))
            
            customBanks.value.push(...newBanks)
            saveCustomBanks()
            updateBankValidator()
            
            alert(`成功导入 ${newBanks.length} 个银行信息！`)
          } else {
            alert('文件格式不正确')
          }
        } catch (error) {
          console.error('导入失败:', error)
          alert('文件解析失败，请检查文件格式')
        }
      }
      
      reader.readAsText(file)
      event.target.value = '' // 清空文件输入
    }
    
    // 更新银行卡验证器
    const updateBankValidator = () => {
      // 触发自定义事件，通知其他组件银行信息已更新
      window.dispatchEvent(new CustomEvent('bankInfoUpdated', {
        detail: { customBanks: customBanks.value }
      }))
    }
    
    // 生命周期
    onMounted(() => {
      loadCustomBanks()
    })
    
    return {
      customBanks,
      searchKeyword,
      newBank,
      editingBank,
      filteredBanks,
      fileInput,
      addBankInfo,
      resetForm,
      editBank,
      updateBank,
      deleteBank,
      exportBankData,
      importBankData,
      handleFileImport
    }
  }
}
</script>

<style scoped>
.bank-info-manager {
  max-width: 1200px;
  margin: 0 auto;
}

.table th {
  font-weight: 600;
  border-top: none;
}

.badge {
  font-size: 0.75em;
}

.form-text {
  font-size: 0.875em;
}

.modal-lg {
  max-width: 800px;
}

@media (max-width: 768px) {
  .table-responsive {
    font-size: 0.875em;
  }
  
  .btn-sm {
    padding: 0.25rem 0.5rem;
    font-size: 0.75rem;
  }
}
</style>